<template>
  <div class="searchTop">
    <form action="/">
      <van-search
        v-model="value"
        show-action
        shape="round"
        background="#3399ff"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
      />
    </form>
    <div class="hot" v-if="isH">
      <!-- 搜索词 -->
      <Hot
        v-if="isDone"
        :list="hotList"
        :value="value"
        @searchHot="searchHot"
      ></Hot>
      <!-- 历史记录 -->
      <History v-else @searchHot="searchHot"></History>
    </div>
    <!-- 搜索到的内容 -->
    <div v-show="isSearch">
      <van-list
        v-if="searchList.length > 0"
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
        @click="isH = false"
        class="list"
      >
        <Item
          v-for="(item, index) in searchList"
          :key="index"
          :item="item"
        ></Item>
      </van-list>
      <div v-else class="wu">暂无数据</div>
    </div>
  </div>
</template>

<script>
import history from '@/components/history.vue'
import hot from '@/components/hot.vue'
import Item from '@/components/item.vue'
import { hotCode, results } from '@/api/search.js'
export default {
  components: {
    [history.name]: history,
    [hot.name]: hot,
    Item
  },
  data () {
    return {
      value: '',
      isDone: false, // 用于控制历史记录和联想切换
      isSearch: false, // 用于控制搜索内容的显示隐藏
      isH: true, // 用于控制提示的显示隐藏
      timer: null, // 用于防抖技术
      obj: {}, // 用于联想缓存技术
      hotList: [],
      historyList: JSON.parse(localStorage.getItem('historyList')) || [],
      searchList: [],
      page: 1,
      loading: false,
      finished: false,
      val: '',
      total_count: 0,
      time: null
    }
  },
  methods: {
    searchHot (test) {
      this.val = test
      this.value = test
      setTimeout(() => this.onSearch(test), 0)
    },
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      const {
        data: { results }
      } = await this.getResults(this.val)
      this.searchList.push(...results)
      // 加载状态结束
      this.loading = false

      // 数据全部加载完成
      if (this.searchList.length >= this.total_count) {
        this.finished = true
      }
    },
    // 确定搜索
    async onSearch (val) {
      if (val) {
        this.isSearch = true
        this.isH = false
        const { data } = await this.getResults(val)
        this.searchList = data.results
        this.page = data.page
        this.val = val
        this.total_count = data.total_count
        const index = this.historyList.findIndex((item) => item === val)
        if (index !== -1) {
          this.historyList.splice(index, 1)
        }
        this.historyList.unshift(val)
        localStorage.setItem('historyList', JSON.stringify(this.historyList))
      } else {
        this.isSearch = false
        this.isH = true
      }
    },
    // 点击取消
    onCancel () {
      this.$router.back()
    },
    // 联想建议
    async getHandler (val) {
      const {
        data: {
          data: { options }
        }
      } = await hotCode(val)
      return options
    },
    // 搜索结果
    async getResults (q) {
      const { data } = await results({
        page: this.page,
        per_page: 10,
        q
      })
      return data
    }
  },
  watch: {
    value: {
      handler (val) {
        if (this.timer) clearTimeout(this.timer)
        this.isH = true
        if (this.isSearch) {
          if (this.time) clearTimeout(this.time)
          this.time = setTimeout(() => {
            this.isH = false
          }, 3000)
        }
        if (val) {
          if (!this.obj[val]) {
            this.timer = setTimeout(async () => {
              this.hotList = await this.getHandler(val)
              this.obj[val] = this.hotList
            }, 700)
          } else {
            this.hotList = this.obj[val]
          }
          console.log(this.obj)
          this.isDone = true
        } else {
          this.isDone = false
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.searchTop {
  position: relative;
}
.hot {
  position: absolute;
  top: 109px;
  left: 0;
  width: 100%;
  background-color: #fff;
  z-index: 999;
}
.list {
  height: calc(100vh - 120px);
  width: 100%;
  overflow: auto;
}
/deep/.van-search__action {
  color: #fff;
}
.wu {
  height: calc(100vh - 120px);
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
